<!DOCTYPE html>
<!-- 版本: 20250822.4 - 增强防缓存 -->
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员后台</title>
    <style>
        /* 基础样式重置 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Arial', sans-serif;
        }

        body {
            background-color: #f5f7fa;
            color: #333;
            line-height: 1.6;
        }

        /* 顶部导航栏 */
        .navbar {
            background-color: #2c3e50;
            color: white;
            padding: 1rem 2rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        .navbar h1 {
            font-size: 1.5rem;
            font-weight: 600;
        }

        .navbar .user-info {
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .navbar .logout-btn {
            background-color: #e74c3c;
            color: white;
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .navbar .logout-btn:hover {
            background-color: #c0392b;
        }

        /* 主容器 */
        .container {
            display: flex;
            min-height: calc(100vh - 60px);
        }

        /* 侧边栏 */
        .sidebar {
            width: 220px;
            background-color: #34495e;
            color: white;
            padding: 1.5rem 0;
        }

        .sidebar-menu {
            list-style: none;
        }

        .sidebar-menu li {
            margin-bottom: 0.5rem;
        }

        .sidebar-menu a {
            color: #ecf0f1;
            text-decoration: none;
            padding: 1rem 1.5rem;
            display: block;
            transition: background-color 0.3s;
        }

        .sidebar-menu a:hover, .sidebar-menu a.active {
            background-color: #2c3e50;
            border-left: 4px solid #3498db;
        }

        /* 主内容区 */
        .main-content {
            flex: 1;
            padding: 2rem;
            overflow-y: auto;
        }

        .content-card {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            padding: 1.5rem;
            margin-bottom: 2rem;
        }

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid #eee;
        }

        .card-header h2 {
            font-size: 1.3rem;
            color: #2c3e50;
        }

        .card-header .btn {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .card-header .btn:hover {
            background-color: #2980b9;
        }

        /* 仪表盘统计卡片 */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }

        .stat-card {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            padding: 1.5rem;
            display: flex;
            flex-direction: column;
        }

        .stat-card .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #2c3e50;
            margin-bottom: 0.5rem;
        }

        .stat-card .stat-label {
            color: #7f8c8d;
            font-size: 0.9rem;
        }

        .stat-card .stat-icon {
            font-size: 2rem;
            color: #3498db;
            margin-bottom: 1rem;
        }

        /* 表格样式 */
        table {
            width: 100%;
            border-collapse: collapse;
        }

        th, td {
            padding: 1rem;
            text-align: left;
            border-bottom: 1px solid #eee;
        }

        th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: #2c3e50;
        }

        tr:hover {
            background-color: #f5f7fa;
        }

        /* 按钮样式 */
        .btn-group {
            display: flex;
            gap: 0.5rem;
        }

        .btn-primary {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .btn-primary:hover {
            background-color: #2980b9;
        }

        .btn-warning {
            background-color: #f39c12;
            color: white;
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .btn-warning:hover {
            background-color: #d35400;
        }

        .btn-danger {
            background-color: #e74c3c;
            color: white;
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .btn-danger:hover {
            background-color: #c0392b;
        }

        /* 表单样式 */
        .form-group {
            margin-bottom: 1.5rem;
        }

        label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 600;
            color: #2c3e50;
        }

        input, select, textarea {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 1rem;
        }

        input:focus, select:focus, textarea:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
        }

        /* 模态框 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.3);
            width: 90%;
            max-width: 600px;
            max-height: 90vh;
            overflow-y: auto;
        }

        .modal-header {
            padding: 1.5rem;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-header h3 {
            font-size: 1.2rem;
            color: #2c3e50;
        }

        .modal-close {
            background: none;
            border: none;
            font-size: 1.5rem;
            cursor: pointer;
            color: #7f8c8d;
        }

        .modal-body {
            padding: 1.5rem;
        }

        .modal-footer {
            padding: 1.5rem;
            border-top: 1px solid #eee;
            display: flex;
            justify-content: flex-end;
            gap: 1rem;
        }

        /* 搜索和过滤 */
        .filter-bar {
            display: flex;
            flex-wrap: wrap;
            gap: 1rem;
            margin-bottom: 1.5rem;
            padding: 1rem;
            background-color: #f8f9fa;
            border-radius: 4px;
        }

        .filter-group {
            flex: 1;
            min-width: 200px;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                flex-direction: column;
            }

            .sidebar {
                width: 100%;
                padding: 1rem 0;
            }

            .sidebar-menu {
                display: flex;
                flex-wrap: wrap;
            }

            .sidebar-menu li {
                margin-bottom: 0;
            }

            .sidebar-menu a {
                padding: 0.75rem 1rem;
                font-size: 0.9rem;
            }

            .stats-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
    <script>
        // 检查登录状态 - 优化版（解决iframe闪烁问题）
        // 版本: 20250822.5 - 修复token初始化问题
        (function() {
            console.log('开始检查登录状态...');
            
            // 添加防缓存响应头
            document.addEventListener('DOMContentLoaded', function() {
                // 设置meta标签防止缓存
                const metaCache = document.createElement('meta');
                metaCache.httpEquiv = 'Cache-Control';
                metaCache.content = 'no-cache, no-store, must-revalidate';
                document.head.appendChild(metaCache);
                
                const metaPragma = document.createElement('meta');
                metaPragma.httpEquiv = 'Pragma';
                metaPragma.content = 'no-cache';
                document.head.appendChild(metaPragma);
                
                const metaExpires = document.createElement('meta');
                metaExpires.httpEquiv = 'Expires';
                metaExpires.content = '0';
                document.head.appendChild(metaExpires);
            });
            
            // 记录重定向次数，防止循环
            let redirectCount = parseInt(sessionStorage.getItem('redirectCount')) || 0;
            console.log('当前重定向计数:', redirectCount);
            
            // 如果重定向次数超过3次，显示错误信息
            if (redirectCount > 3) {
                console.error('检测到可能的循环重定向，已阻止');
                document.write('<h1>错误: 检测到循环重定向</h1><p>请清除浏览器缓存和Cookie后重试。</p>');
                return;
            }
            
            // 增加延迟时间到1000ms，确保localStorage完全可用
            setTimeout(function() {
                const isLoggedIn = localStorage.getItem('isLoggedIn');
                const token = localStorage.getItem('token');
                console.log('isLoggedIn值:', isLoggedIn);
                console.log('token值:', token ? '存在' : '不存在');
                
                if (isLoggedIn !== 'true' || !token) {
                    console.log('未登录、登录状态无效或缺少token，重定向到登录页面');
                    
                    // 增加重定向计数
                    sessionStorage.setItem('redirectCount', (redirectCount + 1).toString());
                    
                    // 方案1: 使用JavaScript重定向
                    window.location.replace('/static/login.html');
                    
                    // 方案2: 添加元标签重定向作为备选
                    const metaRedirect = document.createElement('meta');
                    metaRedirect.httpEquiv = 'refresh';
                    metaRedirect.content = '1; url=/static/login.html';
                    document.head.appendChild(metaRedirect);
                } else {
                    // 验证token有效性
                    try {
                        const payload = JSON.parse(atob(token.split('.')[1]));
                        console.log('Token payload:', payload);
                        console.log('Token expiration:', new Date(payload.exp * 1000));
                        if (payload.exp * 1000 < Date.now()) {
                            console.log('Token expired, redirecting to login');
                            localStorage.removeItem('token');
                            localStorage.setItem('isLoggedIn', 'false');
                            window.location.replace('/static/login.html');
                            return;
                        }
                    } catch (e) {
                        console.error('Error decoding token:', e);
                        localStorage.removeItem('token');
                        localStorage.setItem('isLoggedIn', 'false');
                        window.location.replace('/static/login.html');
                        return;
                    }
                    
                    console.log('已登录且token有效，加载管理员后台');
                    // 将token设置为全局变量，供其他函数使用
                    window.token = token;
                    // 重置重定向计数
                    sessionStorage.removeItem('redirectCount');
                    // 加载用户信息
                    document.addEventListener('DOMContentLoaded', function() {
                        const username = localStorage.getItem('username') || '管理员';
                        document.getElementById('current-user').textContent = username;
                        console.log('已加载用户信息: ' + username);
                        // 初始化页面数据
                        initPage();
                    });
                }
            }, 1000); // 1000毫秒延迟，确保localStorage读取准确
        })();

        // 页面初始化函数
        function initPage() {
            console.log('开始初始化页面...');
            // 加载仪表盘数据
            loadDashboardData();
            // 加载用户列表
            loadUsers();
            // 加载日志
            loadLogs();
            console.log('页面初始化完成');
        }
    </script>
</head>
<body>
    <!-- 顶部导航栏 -->
    <nav class="navbar">
        <h1>管理员后台</h1>
        <div class="user-info">
            <span id="current-user">加载中...</span>
            <button class="logout-btn" id="logout-btn">退出登录</button>
        </div>
    </nav>

    <!-- 主容器 -->
    <div class="container">
        <!-- 侧边栏 -->
        <aside class="sidebar">
            <ul class="sidebar-menu">
                <li><a href="#dashboard" class="active" onclick="showSection('dashboard')">仪表盘</a></li>
                <li><a href="#logs" onclick="showSection('logs')">系统日志</a></li>
                <li><a href="#users" onclick="showSection('users')">用户管理</a></li>
                <li><a href="#model-config" onclick="showSection('model-config')">模型配置</a></li>
            </ul>
        </aside>

        <!-- 主内容区 -->
        <main class="main-content">
            <!-- 仪表盘部分 -->
            <section id="dashboard" class="content-section">
                <div class="content-card">
                    <div class="card-header">
                        <h2>系统概览</h2>
                    </div>
                    <div class="stats-grid">
                        <div class="stat-card">
                            <div class="stat-icon">👥</div>
                            <div class="stat-value" id="user-count">加载中...</div>
                            <div class="stat-label">总用户数</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-icon">🔒</div>
                            <div class="stat-value" id="role-count">加载中...</div>
                            <div class="stat-label">角色数</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-icon">📝</div>
                            <div class="stat-value" id="permission-count">加载中...</div>
                            <div class="stat-label">权限数</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-icon">📄</div>
                            <div class="stat-value" id="document-count">加载中...</div>
                            <div class="stat-label">文档数</div>
                        </div>
                    </div>
                </div>

                <div class="content-card">
                    <div class="card-header">
                        <h2>最近日志</h2>
                    </div>
                    <table id="recent-logs-table">
                        <thead>
                            <tr>
                                <th>时间</th>
                                <th>级别</th>
                                <th>消息</th>
                                <th>来源</th>
                            </tr>
                        </thead>
                        <tbody id="recent-logs-body">
                            <tr><td colspan="4">加载中...</td></tr>
                        </tbody>
                    </table>
                </div>
            </section>

            <!-- 日志查看部分 -->
            <section id="logs" class="content-section" style="display: none;">
                <div class="content-card">
                    <div class="card-header">
                        <h2>系统日志</h2>
                        <button class="btn btn-danger" id="clear-logs-btn">清空日志</button>
                    </div>
                    <div class="filter-bar">
                        <div class="filter-group">
                            <label for="log-start-time">开始时间</label>
                            <input type="datetime-local" id="log-start-time">
                        </div>
                        <div class="filter-group">
                            <label for="log-end-time">结束时间</label>
                            <input type="datetime-local" id="log-end-time">
                        </div>
                        <div class="filter-group">
                            <label for="log-level">日志级别</label>
                            <select id="log-level">
                                <option value="">所有级别</option>
                                <option value="INFO">INFO</option>
                                <option value="WARNING">WARNING</option>
                                <option value="ERROR">ERROR</option>
                            </select>
                        </div>
                        <div class="filter-group">
                            <label for="log-message">消息包含</label>
                            <input type="text" id="log-message" placeholder="输入关键词">
                        </div>
                        <div class="filter-group" style="align-self: flex-end;">
                            <button class="btn btn-primary" id="filter-logs-btn">筛选</button>
                        </div>
                    </div>
                    <table id="logs-table">
                        <thead>
                            <tr>
                                <th>时间</th>
                                <th>级别</th>
                                <th>消息</th>
                                <th>来源</th>
                            </tr>
                        </thead>
                        <tbody id="logs-body">
                            <tr><td colspan="4">加载中...</td></tr>
                        </tbody>
                    </table>
                    <div class="pagination" style="margin-top: 1rem;">
                        <button class="btn btn-primary" id="prev-logs-btn">上一页</button>
                        <span id="logs-page-info">第 1 页 / 共 1 页</span>
                        <button class="btn btn-primary" id="next-logs-btn">下一页</button>
                    </div>
                </div>
            </section>

            <!-- 用户管理部分 -->
            <section id="users" class="content-section" style="display: none;">
                <div class="content-card">
                    <div class="card-header">
                        <h2>用户管理</h2>
                        <button class="btn btn-primary" id="add-user-btn">添加用户</button>
                    </div>
                    <div class="filter-bar">
                        <div class="filter-group">
                            <label for="user-username">用户名</label>
                            <input type="text" id="user-username" placeholder="输入用户名">
                        </div>
                        <div class="filter-group">
                            <label for="user-email">邮箱</label>
                            <input type="text" id="user-email" placeholder="输入邮箱">
                        </div>
                        <div class="filter-group">
                            <label for="user-active">活跃状态</label>
                            <select id="user-active">
                                <option value="">所有状态</option>
                                <option value="true">活跃</option>
                                <option value="false">非活跃</option>
                            </select>
                        </div>
                        <div class="filter-group" style="align-self: flex-end;">
                            <button class="btn btn-primary" id="filter-users-btn">筛选</button>
                        </div>
                    </div>
                    <table id="users-table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>用户名</th>
                                <th>邮箱</th>
                                <th>活跃状态</th>
                                <th>创建时间</th>
                                <th>角色</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="users-body">
                            <tr><td colspan="7">加载中...</td></tr>
                        </tbody>
                    </table>
                    <div class="pagination" style="margin-top: 1rem;">
                        <button class="btn btn-primary" id="prev-users-btn">上一页</button>
                        <span id="users-page-info">第 1 页 / 共 1 页</span>
                        <button class="btn btn-primary" id="next-users-btn">下一页</button>
                    </div>
                </div>
            </section>

            <!-- 模型配置部分 -->
            <section id="model-config" class="content-section" style="display: none;">
                <div class="content-card">
                    <div class="card-header">
                        <h2>模型配置</h2>
                    </div>
                    <form id="model-config-form">
                        <div class="form-group">
                            <label for="deepseek-api-key">DeepSeek API Key</label>
                            <input type="text" id="deepseek-api-key" placeholder="输入DeepSeek API密钥">
                        </div>
                        <div class="form-group">
                            <label for="embedding-model">嵌入模型</label>
                            <input type="text" id="embedding-model" placeholder="输入嵌入模型名称">
                        </div>
                        <div class="form-group">
                            <label for="llm-model">LLM模型</label>
                            <input type="text" id="llm-model" placeholder="输入LLM模型名称">
                        </div>
                        <div class="form-group">
                            <label for="temperature">温度参数</label>
                            <input type="number" id="temperature" step="0.1" min="0" max="1" placeholder="输入温度参数">
                        </div>
                        <div class="form-group">
                            <button type="submit" class="btn btn-primary">保存配置</button>
                        </div>
                    </form>
                </div>
            </section>
        </main>
    </div>

    <!-- 添加/编辑用户模态框 -->
    <div class="modal" id="user-modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="user-modal-title">添加用户</h3>
                <button class="modal-close" id="user-modal-close">&times;</button>
            </div>
            <div class="modal-body">
                <form id="user-form">
                    <input type="hidden" id="user-id">
                    <div class="form-group">
                        <label for="modal-username">用户名</label>
                        <input type="text" id="modal-username" required>
                    </div>
                    <div class="form-group">
                        <label for="modal-email">邮箱</label>
                        <input type="email" id="modal-email" required>
                    </div>
                    <div class="form-group">
                        <label for="modal-password">密码</label>
                        <input type="password" id="modal-password" placeholder="不填则不修改">
                    </div>
                    <div class="form-group">
                        <label for="modal-active">活跃状态</label>
                        <select id="modal-active">
                            <option value="true">活跃</option>
                            <option value="false">非活跃</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="modal-roles">角色</label>
                        <select id="modal-roles" multiple style="height: 100px;">
                            <!-- 角色选项将通过JavaScript动态加载 -->
                        </select>
                        <small>按住Ctrl键可多选</small>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn" id="user-modal-cancel">取消</button>
                <button class="btn btn-primary" id="user-modal-save">保存</button>
            </div>
        </div>
    </div>

    <!-- JavaScript -->
    <script>
        // 当前页面状态
        let currentSection = 'dashboard';
        let currentLogsPage = 1;
        let currentUsersPage = 1;
        let totalLogsPages = 1;
        let totalUsersPages = 1;
        let token = null;

        // DOM元素
        const sections = document.querySelectorAll('.content-section');
        const sidebarLinks = document.querySelectorAll('.sidebar-menu a');
        const userModal = document.getElementById('user-modal');

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 从localStorage获取token
            token = localStorage.getItem('token');
            console.log('Token from localStorage:', token);
            if (!token) {
                console.log('No token found, redirecting to login');
                window.location.href = '/static/auth_test_v2.html';
                return;
            }

            // 解码token以查看其内容（仅用于调试）
            try {
                const tokenParts = token.split('.');
                if (tokenParts.length === 3) {
                    const payload = JSON.parse(atob(tokenParts[1]));
                    console.log('Token payload:', payload);
                    console.log('Token expiration:', new Date(payload.exp * 1000));
                    if (payload.exp * 1000 < Date.now()) {
                        console.log('Token expired, redirecting to login');
                        localStorage.removeItem('token');
                        window.location.href = '/static/auth_test_v2.html';
                        return;
                    }
                }
            } catch (e) {
                console.error('Error decoding token:', e);
            }

            // 加载当前用户信息
            loadCurrentUser();

            // 加载仪表盘数据
            loadDashboardData();

            // 立即加载用户列表、角色列表和模型配置以测试接口
            loadUsers();
            loadRoles();
            loadModelConfig();

            // 注册事件监听器
            registerEventListeners();
        });

        // 切换显示部分
        function showSection(sectionId) {
            // 更新当前部分
            currentSection = sectionId;

            // 隐藏所有部分
            sections.forEach(section => {
                section.style.display = 'none';
            });

            // 显示选中部分
            document.getElementById(sectionId).style.display = 'block';

            // 更新侧边栏链接状态
            sidebarLinks.forEach(link => {
                link.classList.remove('active');
                if (link.getAttribute('href') === '#' + sectionId) {
                    link.classList.add('active');
                }
            });

            // 按需加载数据
            if (sectionId === 'logs') {
                loadLogs();
            } else if (sectionId === 'users') {
                loadUsers();
                loadRoles();
            } else if (sectionId === 'model-config') {
                loadModelConfig();
            }
        }

        // 注册事件监听器
        function registerEventListeners() {
            // 侧边栏链接点击事件
            sidebarLinks.forEach(link => {
                link.addEventListener('click', function(e) {
                    e.preventDefault();
                    const sectionId = this.getAttribute('href').substring(1);
                    showSection(sectionId);
                });
            });

            // 退出登录按钮点击事件
            document.getElementById('logout-btn').addEventListener('click', function() {
                localStorage.removeItem('token');
                localStorage.setItem('isLoggedIn', 'false');  // 确保状态一致
                window.location.href = '/static/login.html';
            });

            // 日志相关按钮事件
            // 确保筛选按钮点击事件正确绑定
            const filterBtn = document.getElementById('filter-logs-btn');
            if (filterBtn) {
                filterBtn.addEventListener('click', function() {
                    currentLogsPage = 1;
                    console.log('筛选按钮被点击，调用loadLogs()');
                    loadLogs();
                });
                console.log('筛选按钮事件绑定成功');
            } else {
                console.error('未找到筛选按钮元素');
            }

            // 添加测试按钮事件，用于验证message_contains参数
            const testFilterBtn = document.createElement('button');
            testFilterBtn.id = 'test-filter-btn';
            testFilterBtn.textContent = '测试日志筛选';
            testFilterBtn.className = 'btn btn-primary';
            testFilterBtn.style.marginLeft = '10px';
            filterBtn.parentNode.appendChild(testFilterBtn);

            testFilterBtn.addEventListener('click', function() {
                console.log('测试按钮被点击，设置message_contains为"测试"');
                document.getElementById('log-message').value = '测试';
                currentLogsPage = 1;
                loadLogs();
            });
            console.log('测试按钮创建并绑定事件成功');

            document.getElementById('clear-logs-btn').addEventListener('click', function() {
                if (confirm('确定要清空所有日志吗？')) {
                    clearLogs();
                }
            });

            document.getElementById('prev-logs-btn').addEventListener('click', function() {
                if (currentLogsPage > 1) {
                    currentLogsPage--;
                    loadLogs();
                }
            });

            document.getElementById('next-logs-btn').addEventListener('click', function() {
                if (currentLogsPage < totalLogsPages) {
                    currentLogsPage++;
                    loadLogs();
                }
            });

            // 用户相关按钮事件
            document.getElementById('add-user-btn').addEventListener('click', function() {
                showUserModal();
            });

            document.getElementById('filter-users-btn').addEventListener('click', function() {
                currentUsersPage = 1;
                loadUsers();
            });

            document.getElementById('prev-users-btn').addEventListener('click', function() {
                if (currentUsersPage > 1) {
                    currentUsersPage--;
                    loadUsers();
                }
            });

            document.getElementById('next-users-btn').addEventListener('click', function() {
                if (currentUsersPage < totalUsersPages) {
                    currentUsersPage++;
                    loadUsers();
                }
            });

            // 用户模态框相关按钮事件
            document.getElementById('user-modal-close').addEventListener('click', function() {
                hideUserModal();
            });

            document.getElementById('user-modal-cancel').addEventListener('click', function() {
                hideUserModal();
            });

            document.getElementById('user-modal-save').addEventListener('click', function() {
                saveUser();
            });

            // 模型配置表单提交事件
            document.getElementById('model-config-form').addEventListener('submit', function(e) {
                e.preventDefault();
                saveModelConfig();
            });
        }

        // 加载当前用户信息
        function loadCurrentUser() {
            fetch('/users/me', {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('获取用户信息失败');
                }
                return response.json();
            })
            .then(user => {
                document.getElementById('current-user').textContent = user.username;
            })
            .catch(error => {
                console.error('加载当前用户信息失败:', error);
                alert('加载当前用户信息失败，请重新登录');
                localStorage.removeItem('token');
                localStorage.setItem('isLoggedIn', 'false');
                window.location.href = '/static/login.html';
            });
        }

        // 加载仪表盘数据
        function loadDashboardData() {
            console.log('正在加载仪表盘数据...');
            fetch('/admin/dashboard', {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('获取仪表盘数据失败');
                }
                return response.json();
            })
            .then(data => {
                // 更新统计数据
                document.getElementById('user-count').textContent = data.dashboard.user_count;
                document.getElementById('role-count').textContent = data.dashboard.role_count;
                document.getElementById('permission-count').textContent = data.dashboard.permission_count;
                document.getElementById('document-count').textContent = data.dashboard.document_count;

                // 更新最近日志
                const logsBody = document.getElementById('recent-logs-body');
                logsBody.innerHTML = '';

                if (data.recent_logs && data.recent_logs.length > 0) {
                    data.recent_logs.forEach(log => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${new Date(log.timestamp).toLocaleString()}</td>
                            <td>${log.level}</td>
                            <td>${log.message}</td>
                            <td>${log.source}</td>
                        `;
                        logsBody.appendChild(row);
                    });
                } else {
                    logsBody.innerHTML = '<tr><td colspan="4">暂无日志</td></tr>';
                }
            })
            .catch(error => {
                console.error('加载仪表盘数据失败:', error);
                alert('加载仪表盘数据失败: ' + error.message);
            });
        }

        // 添加刷新按钮事件
        document.addEventListener('DOMContentLoaded', function() {
            // 创建刷新按钮
            const refreshBtn = document.createElement('button');
            refreshBtn.id = 'refresh-dashboard';
            refreshBtn.className = 'btn btn-primary';
            refreshBtn.textContent = '刷新数据';
            refreshBtn.style.margin = '10px 0';
            
            // 添加到页面
            const dashboardContainer = document.querySelector('.dashboard-container');
            if (dashboardContainer) {
                dashboardContainer.insertBefore(refreshBtn, dashboardContainer.firstChild);
            }
            
            // 绑定点击事件
            refreshBtn.addEventListener('click', function() {
                loadDashboardData();
                alert('数据已刷新');
            });
            
            // 设置自动刷新（每30秒）
            setInterval(loadDashboardData, 30000);
            console.log('已设置自动刷新，每30秒更新一次数据');
        })

        // 加载日志
        function loadLogs() {
            const start_time = document.getElementById('log-start-time').value;
            const end_time = document.getElementById('log-end-time').value;
            const level = document.getElementById('log-level').value;
            const message_contains = document.getElementById('log-message').value;
            const limit = 20;
            const offset = (currentLogsPage - 1) * limit;

            // 添加调试信息
            console.log('日志筛选参数:');
            console.log('start_time:', start_time, '类型:', typeof start_time);
            console.log('end_time:', end_time, '类型:', typeof end_time);
            console.log('level:', level, '类型:', typeof level);
            console.log('message_contains:', message_contains, '类型:', typeof message_contains);

            let url = `/admin/logs?limit=${limit}&offset=${offset}`;
            if (start_time !== '') url += `&start_time=${encodeURIComponent(start_time)}`;
            if (end_time !== '') url += `&end_time=${encodeURIComponent(end_time)}`;
            if (level !== '') url += `&level=${encodeURIComponent(level)}`;
            // 始终添加message_contains参数，即使为空
            const messageValue = message_contains || '';
            url += `&message_contains=${encodeURIComponent(messageValue)}`;
            console.log('请求URL:', url);
            console.log('筛选按钮被点击，开始加载日志...');
            console.log('最终message_contains值:', messageValue);
            console.log('最终URL参数:', new URLSearchParams(url.split('?')[1]));


            fetch(url, {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('获取日志失败');
                }
                return response.json();
            })
            .then(data => {
                const logsBody = document.getElementById('logs-body');
                logsBody.innerHTML = '';

                if (data.logs && data.logs.length > 0) {
                    data.logs.forEach(log => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${new Date(log.timestamp).toLocaleString()}</td>
                            <td>${log.level}</td>
                            <td>${log.message}</td>
                            <td>${log.source}</td>
                        `;
                        logsBody.appendChild(row);
                    });

                    // 更新分页信息
                    totalLogsPages = Math.ceil(data.total / limit);
                    document.getElementById('logs-page-info').textContent = `第 ${currentLogsPage} 页 / 共 ${totalLogsPages} 页`;
                } else {
                    logsBody.innerHTML = '<tr><td colspan="4">暂无日志</td></tr>';
                    document.getElementById('logs-page-info').textContent = '第 1 页 / 共 1 页';
                }
            })
            .catch(error => {
                console.error('加载日志失败:', error);
                alert('加载日志失败');
            });
        }

        // 清空日志
        function clearLogs() {
            fetch('/admin/logs', {
                method: 'DELETE',
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('清空日志失败');
                }
                return response.json();
            })
            .then(data => {
                alert('日志已清空');
                loadLogs();
            })
            .catch(error => {
                console.error('清空日志失败:', error);
                alert('清空日志失败');
            });
        }

        // 加载用户
        function loadUsers() {
            const username = document.getElementById('user-username').value;
            const email = document.getElementById('user-email').value;
            const is_active = document.getElementById('user-active').value;
            const limit = 20;
            const offset = (currentUsersPage - 1) * limit;

            let url = `/admin/users?limit=${limit}&offset=${offset}`;
            if (username) url += `&username=${encodeURIComponent(username)}`;
            if (email) url += `&email=${encodeURIComponent(email)}`;
            if (is_active) url += `&is_active=${encodeURIComponent(is_active)}`;

            fetch(url, {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('获取用户列表失败');
                }
                return response.json();
            })
            .then(data => {
                const usersBody = document.getElementById('users-body');
                usersBody.innerHTML = '';

                if (data.users && data.users.length > 0) {
                    data.users.forEach(user => {
                            const row = document.createElement('tr');
                            // 格式化创建时间
                            const createdAt = user.created_at ? new Date(user.created_at).toLocaleString() : '';
                            // 确保roles存在且是数组
                            const roles = user.roles && Array.isArray(user.roles) ? user.roles : [];
                            // 活跃状态显示
                            const activeStatus = user.is_active ? '活跃' : '非活跃';

                            row.innerHTML = `
                                <td>${user.id || ''}</td>
                                <td>${user.username || ''}</td>
                                <td>${user.email || ''}</td>
                                <td>${activeStatus}</td>
                                <td>${createdAt}</td>
                                <td>${roles.map(role => role.name).join(', ')}</td>
                                <td class="btn-group">
                                    <button class="btn btn-warning" onclick="editUser('${user.id || ''}')">编辑</button>
                                    <button class="btn btn-danger" onclick="deleteUser('${user.id || ''}', '${user.username || ''}')">删除</button>
                                </td>
                            `;
                            usersBody.appendChild(row);
                        });

                    // 更新分页信息
                    totalUsersPages = Math.ceil(data.total / limit);
                    document.getElementById('users-page-info').textContent = `第 ${currentUsersPage} 页 / 共 ${totalUsersPages} 页`;
                } else {
                    usersBody.innerHTML = '<tr><td colspan="7">暂无用户</td></tr>';
                    document.getElementById('users-page-info').textContent = '第 1 页 / 共 1 页';
                }
            })
            .catch(error => {
                console.error('加载用户列表失败:', error);
                alert('加载用户列表失败');
            });
        }

        // 加载角色
        function loadRoles() {
            // 调用专门的角色API获取角色列表
            return fetch('/admin/roles', {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('获取角色列表失败');
                }
                return response.json();
            })
            .then(data => {
                if (data.roles && data.roles.length > 0) {
                    const rolesSelect = document.getElementById('modal-roles');
                    rolesSelect.innerHTML = '';
                    data.roles.forEach(role => {
                        const option = document.createElement('option');
                        option.value = role.id;
                        option.textContent = role.name;
                        rolesSelect.appendChild(option);
                    });
                }
                return data;  // 返回数据以便后续处理
            })
            .catch(error => {
                console.error('加载角色列表失败:', error);
                throw error;  // 重新抛出错误以便调用者处理
            });
        }

        // 显示用户模态框
        function showUserModal(userId = null) {
            const modalTitle = document.getElementById('user-modal-title');
            const userIdInput = document.getElementById('user-id');
            const usernameInput = document.getElementById('modal-username');
            const emailInput = document.getElementById('modal-email');
            const passwordInput = document.getElementById('modal-password');
            const activeSelect = document.getElementById('modal-active');
            const rolesSelect = document.getElementById('modal-roles');

            // 重置表单
            userIdInput.value = '';
            usernameInput.value = '';
            emailInput.value = '';
            passwordInput.value = '';
            activeSelect.value = 'true';
            // 清空角色选择
            while (rolesSelect.options.length > 0) {
                rolesSelect.remove(0);
            }

            if (userId) {
                // 编辑用户
                modalTitle.textContent = '编辑用户';
                userIdInput.value = userId;

                // 加载用户信息
                fetch(`/admin/users/${userId}`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('获取用户信息失败');
                    }
                    return response.json();
                })
                .then(user => {
                    usernameInput.value = user.username;
                    emailInput.value = user.email;
                    activeSelect.value = user.is_active.toString();

                    // 加载角色并设置选中状态
                    loadRoles().then(() => {
                        if (user.roles) {
                            user.roles.forEach(userRole => {
                                for (let i = 0; i < rolesSelect.options.length; i++) {
                                    if (rolesSelect.options[i].value === userRole.id) {
                                        rolesSelect.options[i].selected = true;
                                        break;
                                    }
                                }
                            });
                        }
                    });
                })
                .catch(error => {
                    console.error('加载用户信息失败:', error);
                    alert('加载用户信息失败');
                    hideUserModal();
                });
            } else {
                // 添加用户
                modalTitle.textContent = '添加用户';
                // 加载角色
                loadRoles();
            }

            // 显示模态框
            userModal.style.display = 'flex';
        }

        // 隐藏用户模态框
        function hideUserModal() {
            userModal.style.display = 'none';
        }

        // 保存用户
        function saveUser() {
            const userId = document.getElementById('user-id').value;
            const username = document.getElementById('modal-username').value;
            const email = document.getElementById('modal-email').value;
            const password = document.getElementById('modal-password').value;
            const isActive = document.getElementById('modal-active').value === 'true';
            const rolesSelect = document.getElementById('modal-roles');
            const roleIds = Array.from(rolesSelect.selectedOptions).map(option => option.value);

            // 验证表单
            if (!username || !email) {
                alert('用户名和邮箱不能为空');
                return;
            }

            // 准备数据
            const userData = {
                username: username,
                email: email,
                is_active: isActive,
                role_ids: roleIds
            };

            // 如果填写了密码，则添加到数据中
            if (password) {
                userData.password = password;
            }

            // 确定请求方法和URL
            let method, url;
            if (userId) {
                method = 'PUT';
                url = `/admin/users/${userId}`;
            } else {
                method = 'POST';
                url = '/users';  // 使用现有的创建用户API
            }

            // 发送请求
            fetch(url, {
                method: method,
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(userData)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(userId ? '更新用户失败' : '添加用户失败');
                }
                return response.json();
            })
            .then(data => {
                alert(userId ? '用户已更新' : '用户已添加');
                hideUserModal();
                loadUsers();
            })
            .catch(error => {
                console.error(userId ? '更新用户失败:' : '添加用户失败:', error);
                alert(userId ? '更新用户失败' : '添加用户失败');
            });
        }

        // 删除用户
        function deleteUser(userId, username) {
            if (confirm(`确定要删除用户 ${username} 吗？`)) {
                fetch(`/admin/users/${userId}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('删除用户失败');
                    }
                    return response.json();
                })
                .then(data => {
                    alert('用户已删除');
                    loadUsers();
                })
                .catch(error => {
                    console.error('删除用户失败:', error);
                    alert('删除用户失败');
                });
            }
        }

        // 加载模型配置
        function loadModelConfig() {
            fetch('/admin/model-config', {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('获取模型配置失败');
                }
                return response.json();
            })
            .then(config => {
                document.getElementById('deepseek-api-key').value = config.deepseek_api_key || '';
                document.getElementById('embedding-model').value = config.embedding_model || '';
                document.getElementById('llm-model').value = config.llm_model || '';
                document.getElementById('temperature').value = config.temperature || '';
            })
            .catch(error => {
                console.error('获取模型配置失败:', error);
                alert('获取模型配置失败');
            });
        }

        // 编辑用户 - 添加editUser函数作为showUserModal的别名
function editUser(userId) {
    showUserModal(userId);
}

// 保存模型配置
function saveModelConfig() {
            const deepseekApiKey = document.getElementById('deepseek-api-key').value;
            const embeddingModel = document.getElementById('embedding-model').value;
            const llmModel = document.getElementById('llm-model').value;
            const temperature = document.getElementById('temperature').value;

            // 准备数据
            const configData = {};
            if (deepseekApiKey) configData.deepseek_api_key = deepseekApiKey;
            if (embeddingModel) configData.embedding_model = embeddingModel;
            if (llmModel) configData.llm_model = llmModel;
            if (temperature) configData.temperature = parseFloat(temperature);

            // 发送请求
            fetch('/admin/model-config', {
                method: 'PUT',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(configData)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('保存模型配置失败');
                }
                return response.json();
            })
            .then(data => {
                alert('模型配置已保存');
            })
            .catch(error => {
                console.error('保存模型配置失败:', error);
                alert('保存模型配置失败');
            });
        }
    </script>
</body>
</html>